# -*- coding:utf-8 -*-
# @Time:2023/10/25 19:27
# @Author: cevent
# @name=用户认证类
from django.contrib.auth.backends import ModelBackend
import re
from users.models import User


# 使用用户名查询用户对象
def getUserInfoByAccount(account):
    try:
        # 判断手机号
        if re.match(r'^1[3-9]\d{9}$', account):
            user = User.objects.get(mobile=account)
        else:
            user = User.objects.get(username=account)

    except User.DoesNotExist:
        return None
    else:
        return user


# 1.自定义用户登录认证：用户名/手机号
class MyAuthenticateLoginUser(ModelBackend):
    print('进入手机号/用户名认证')

    # 重写authenticate登录认证
    def authenticate(self, requests, username=None, password=None, **kwargs):
        print('获取参数username: ', username, password)
        # 非空判断
        if username is None or password is None:
            return

        user = getUserInfoByAccount(username)
        if user and user.check_password(password):
            return user
        else:
            return None
